﻿using System;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Data;

namespace Zuehlke.Blueprint.Quickstart.Architecture.Presentation.UserInterface.ValueConverters
{
    /// <summary>
    /// Truncates a string to the specified length and adds a suffix to it.
    /// </summary>
    public class StringTruncateConverter : ValueConverterMarkupExtensionBase, IValueConverter
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="StringTruncateConverter"/> class.
        /// </summary>
        public StringTruncateConverter(int length)
        {
            Length = length;
            Suffix = ".";
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets the length.
        /// </summary>
        public int Length { get; set; }

        /// <summary>
        /// Gets or sets the suffix.
        /// </summary>
        public string Suffix { get; set; }

        #endregion

        #region IValueConverter Members

        /// <summary>
        /// See <see cref="IValueConverter.Convert"/>.
        /// </summary>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return DependencyProperty.UnsetValue;
            }

            var valueStringBuilder = new StringBuilder(value.ToString());
            if(valueStringBuilder.Length > Length)
            {
                valueStringBuilder.Length = Length;
            }
            valueStringBuilder.Append(Suffix);

            return valueStringBuilder.ToString();
        }

        /// <summary>
        /// See <see cref="IValueConverter.ConvertBack"/>.
        /// </summary> 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}
